﻿/*
 * PsTFS is a set of PowerShell commands to manage and use Team Foundation Server. PowerShell 
 * effectiveness is combined with the power of TFS API to maximizes TFS capabilities.
 * 
 * Creator : Choulant Noham
 * Mail : choulant@gmail.com
 * Blog : http://choulant.blogspot.com
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using PsTFS.Methodes;
using PsTFS.Objects;

namespace PsTFS.Commandes.Get
{
    /// <summary>
    /// Récupération d'un WorkItem
    /// </summary>
    [Cmdlet(VerbsCommon.Get, "ChangesetByWI")]
    public class GetChangesetByWI : PsCmdlet
    {
        /// <summary>
        /// Lancement du processus de récupéraiton des changesets
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                var changesets = new List<Changeset>();
                if (WIs == null)
                {
                    WIs = new List<WorkItem>();
                }
                if (WI != null)
                {
                    WIs.Add(WI);
                }

                if (WIs.Count > 0)
                {

                    changesets =
                        (WIs.SelectMany(w => w.ListChangeset())).Distinct().OrderBy(cs => cs.ChangesetId).ToList();
                }
                WriteObject(changesets.Distinct().ToList(), false);
            }
            catch (Exception ex)
            {
                var err = ErrorRecord(ex,ErrorCategory.WriteError);
                WriteError(err);
                Log.AddLog(ex.StackTrace);
            }
            finally
            {
                base.ProcessRecord();
            }
        }

        /// <summary>
        /// Permet d'informer la fin de la commande
        /// </summary>
        protected override void EndProcessing()
        {
            Log.AddLog(null, "GetChangesetByWI is end");
            base.EndProcessing();
        }

        /// <summary>
        /// Element de travail unique pour la récupération du changeset
        /// </summary>
        [Parameter(Position = 0)]
        [ValidateNotNullOrEmpty]
// ReSharper disable InconsistentNaming
        public WorkItem WI { get; set; }
// ReSharper restore InconsistentNaming

        /// <summary>
        /// Collection d'élement de travail pour la récupération du changeset
        /// </summary>
        [Parameter(Position = 1)]
        [ValidateNotNullOrEmpty]
        public List<WorkItem> WIs { get; set; }

    }
}